package com.dabai.iot.core.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dabai.common.core.enums.FormatsType;
import com.dabai.common.core.utils.DateUtils;
import com.dabai.common.core.utils.ObjectUtils;
import com.dabai.common.redis.utils.RedisUtils;
import com.dabai.common.tenant.helper.TenantHelper;
import com.dabai.iot.core.cache.CacheKey;
import com.dabai.iot.core.entity.DeviceCountEntity;
import com.dabai.iot.core.mapper.DeviceCountMapper;
import com.dabai.iot.core.service.IDeviceCountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Set;

/**
 * 在线设备数量表 Service 实现类
 *
 * @author kev1n
 */
@Slf4j
@Service
public class DeviceCountServiceImpl extends ServiceImpl<DeviceCountMapper, DeviceCountEntity> implements IDeviceCountService {

    /**
     * 保存指定日期的设备最大在线数量到数据库
     */
    @Override
    public void saveOnlineCount(String tenantId, Date date, Long count) {
        String dateStr = DateUtils.parseDateToStr(FormatsType.YYYYMMDD, date);

        DeviceCountEntity deviceCount = lambdaQuery().eq(DeviceCountEntity::getTenantId, tenantId).eq(DeviceCountEntity::getDate, dateStr).one();
        if (deviceCount == null) {
            deviceCount = new DeviceCountEntity();
        }

        Date now = DateUtil.date();
        deviceCount.setTenantId(tenantId);
        deviceCount.setDate(dateStr);
        deviceCount.setOnlineCount(count);
        if (deviceCount.getId() == null) {
            deviceCount.setCreateTime(now);
        }
        deviceCount.setUpdateTime(now);

        if (saveOrUpdate(deviceCount)) {
            deleteDeviceOnlineCount(tenantId, date);
        }
    }

    /**
     * 获取数据库中指定日期的设备最大在线数量
     */
    @Override
    public Long getCount(String tenantId, String date) {
        DeviceCountEntity deviceCount = lambdaQuery().eq(DeviceCountEntity::getTenantId, tenantId).eq(DeviceCountEntity::getDate, date).one();
        if (deviceCount == null) {
            return 0L;
        } else {
            return deviceCount.getOnlineCount();
        }
    }

    /**
     * 更新缓存中指定日期的在线设备集合
     */
    @Override
    public void updateDeviceOnlineCount(String tenantId, Date date, Set<Long> deviceIds) {
        String dateStr = DateUtil.format(date, "yyyyMMdd");
        String countKey = CacheKey.getDeviceCountKey(tenantId, dateStr);
        TenantHelper.ignore(() -> RedisUtils.setCacheSet(countKey, deviceIds));

        log.info("更新缓存中在线设备集合，date={}，tenantId={}，deviceIds={}", dateStr, tenantId, deviceIds);
    }

    /**
     * 获取缓存中指定日期的在线设备数量
     */
    @Override
    public long getDeviceOnlineCount(String tenantId, Date date) {
        String dateStr = DateUtils.parseDateToStr(FormatsType.YYYYMMDD, date);
        String countKey = CacheKey.getDeviceCountKey(tenantId, dateStr);
        Set<Long> onlineDeviceIds = TenantHelper.ignore(() -> RedisUtils.getCacheSet(countKey));

        if (ObjectUtils.isNotEmpty(onlineDeviceIds)) {
            return onlineDeviceIds.size();
        }
        return 0;
    }

    /**
     * 删除缓存中指定日期的在线设备数量
     */
    @Override
    public void deleteDeviceOnlineCount(String tenantId, Date date) {
        String dateStr = DateUtils.parseDateToStr(FormatsType.YYYYMMDD, date);
        String countKey = CacheKey.getDeviceCountKey(tenantId, dateStr);
        TenantHelper.ignore(() -> RedisUtils.deleteObject(countKey));
    }

}
